package com.antdesignbackend.backend.news.notice.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.news.news.entity.News;
import com.antdesignbackend.backend.news.noticeusers.entity.NoticeUsers;
import com.antdesignbackend.backend.news.noticeusers.entity.entityVo.NoticeUsersVo;
import com.antdesignbackend.backend.news.noticeusers.service.NoticeUsersService;
import com.antdesignbackend.backend.service.UserService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.news.notice.entity.Notice;
import com.antdesignbackend.backend.news.notice.entity.entityVo.NoticeVo;
import com.antdesignbackend.backend.news.notice.service.NoticeService;

/**
 * 公告管理
 *
 * @author 不二
 * @email notice
 * @date 2020-07-25 18:11:33
 */

@Controller
@RequestMapping("/notice")
@Slf4j
public class NoticeController extends BaseController{

	private static final String FUN_NAME = "公告管理";//功能名称
	private Integer nid;

	@Autowired
	private NoticeService noticeService;

	@Autowired
	private UserService userService;

	@Autowired
	NoticeUsersService noticeUsersService;

	@GetMapping("/index")
	@AuthToken
	public String index() {
		return "news/notice/index";
	}

	@GetMapping("/push/{id}")
	@AuthToken
	public String push(@PathVariable("id") Integer id) {
		this.nid = id;
		return "news/notice/push";
	}

	@GetMapping("/mobile/{id}")
	@AuthToken
	public String mobile(@PathVariable("id") Integer id, Model model) {
		NoticeUsers noticeUsers = noticeUsersService.getById(id);
		if (noticeUsers == null){
			return "404";
		}
		if (noticeUsers.getStatus() == 0){
			noticeUsers.setStatus(1);
			noticeUsersService.updateById(noticeUsers);
		}
		//根据消息id查询消息
		Notice notice = noticeService.getById(noticeUsers.getNid());
		if (notice == null){
			return "404";
		}
		model.addAttribute("notice",notice);
		return "news/notice/mobile";
	}

	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody NoticeVo noticeVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		List<NoticeVo> list = new ArrayList<>();
		QueryWrapper<NoticeVo> wrapper = new QueryWrapper<>();
		//判断用户权限
		Users users = userService.getById(getLoginUserId());
		if (users.getAuthType() == 1){ //地市权限
			wrapper.eq("authCity",users.getAuthCity());
		}else if (users.getAuthType() == 2){ //区县权限
			wrapper.eq("authDistrict",users.getAuthDistrict());
		}else if (users.getAuthType() == 3){
			wrapper.eq("authTown",users.getAuthTown());
		}else {
			return result;
		}
		if(noticeVo.getAuthCity() != null && noticeVo.getAuthCity() != -1){
			wrapper.eq("authCity",noticeVo.getAuthCity());
		}
		if(noticeVo.getAuthDistrict() != null && noticeVo.getAuthDistrict() != -1){
			wrapper.eq("authDistrict",noticeVo.getAuthDistrict());
		}
		if(noticeVo.getAuthTown() != null && noticeVo.getAuthTown() != -1){
			wrapper.eq("authTown",noticeVo.getAuthTown());
		}
		if (noticeVo.getType() != null){
			wrapper.eq("type",noticeVo.getType());
		}
		if (noticeVo.getTitle() != null && !noticeVo.getTitle().equals("")){
			wrapper.like("title",noticeVo.getTitle());
		}
		wrapper.orderByDesc("CreateTime");
		int total = noticeService.count(wrapper);
		if (total > 0){
			list = noticeService.search(wrapper,new Page<NoticeVo>(noticeVo.getPageIndex(),noticeVo.getPageSize()));
			if (list.size() > 0){
				for (NoticeVo notice:list){
					StringBuilder rolesName = new StringBuilder();
					if (notice.getRoles() != null && !notice.getRoles().equals("")){
						String[] strings = notice.getRoles().split(",");
						for (String s:strings){
							if ("2".equals(s)){
								rolesName.append("执法管理人员,");
							}else if ("6".equals(s)){
								rolesName.append("检疫人员,");
							}else if ("3".equals(s)){
								rolesName.append("养殖企业,");
							}else if ("4".equals(s)){
								rolesName.append("屠宰企业,");
							}else if ("5".equals(s)){
								rolesName.append("无害化处理企业,");
							}
						}
					}
					String rolesName1 = "";
					if (rolesName.length() > 0){
						rolesName1 =  rolesName.substring(0,rolesName.length() - 1);
					}
					notice.setRolesName(rolesName1);
					//去掉内容html标签，用于显示
					if (notice.getContent() != null){
						String showContent = notice.getContent().replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
						if (showContent.length() > 7){
							showContent = showContent.substring(0,7) + "...";
						}
						notice.setShowContent(showContent);
					}

					//拼接文件路径
					if (notice.getEnclosure()!=null && !notice.getEnclosure().equals(""))
						notice.setEnclosure(WebConfig.host + "enclosure/" + notice.getEnclosure());
				}
			}
		}
		result.setTotal(total);
		result.setData(list);
		return result;
	}

	@GetMapping("/getById/{id}")
	@ResponseBody
	public	Notice getById(@PathVariable(name = "id") String id) {
		Notice obj = noticeService.getById(id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody Notice notice){
		ReturnVO result = new ReturnVO();
		notice.setCreateUid(getLoginUserId());
		notice.setCreateTime(new Date());
		try {
			noticeService.createNotice(notice);
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody Notice notice){
		ReturnVO result = new ReturnVO();
		notice.setCreateUid(getLoginUserId());
		notice.setCreateTime(new Date());
		try {
			noticeService.updateNotice(notice);
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		if (noticeService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}

	public static void main(String[] args) {
		String content = "<p><img src=\"http://localhost:18080/images/1596014041170.jpg\" style=\"max-width:100%;\">各位养殖户注意了<br></p>";
		content = content.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
		System.out.println(content);
	}

	@PostMapping("/tableSearchPush")
	@ResponseBody
	ReturnVO tableSearchPush(@RequestBody NoticeUsersVo noticeUsersVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		List<NoticeUsersVo> list = new ArrayList<>();
		QueryWrapper<NoticeUsersVo> wrapper = new QueryWrapper<>();

		if (noticeUsersVo.getStatus() != null && noticeUsersVo.getStatus() != -1){
			wrapper.eq("status",noticeUsersVo.getStatus());
		}
		if (noticeUsersVo.getUserName() != null && !noticeUsersVo.getUserName().equals("")){
			wrapper.eq("UserName",noticeUsersVo.getUserName());
		}
		if (noticeUsersVo.getPhone() != null && !noticeUsersVo.getPhone().equals("")){
			wrapper.eq("Phone",noticeUsersVo.getPhone());
		}
		if (noticeUsersVo.getEnterpriseName() != null && !noticeUsersVo.getEnterpriseName().equals("")){
			wrapper.eq("EnterpriseName",noticeUsersVo.getEnterpriseName());
		}
		wrapper.eq("nid",nid);
		wrapper.orderByDesc("CreateTime");
		//查询总数
		int total = noticeUsersService.count(wrapper);
		if (total > 0){
			list = noticeUsersService.search(wrapper,new Page<NoticeUsersVo>(noticeUsersVo.getPageIndex(),noticeUsersVo.getPageSize()));
			if (list.size() > 0){
				for (NoticeUsersVo noticeUsersVo1:list){
					//去掉内容html标签，用于显示
					if (noticeUsersVo1.getContent() != null){
						String showContent = noticeUsersVo1.getContent().replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
						if (showContent.length() > 16){
							showContent = showContent.substring(0,16) + "...";
						}
						noticeUsersVo1.setContent(showContent);
					}
					//拼接文件路径
					if (noticeUsersVo1.getEnclosure()!=null && !noticeUsersVo1.getEnclosure().equals(""))
						noticeUsersVo1.setEnclosure(WebConfig.host + "enclosure/" + noticeUsersVo1.getEnclosure());
				}
			}
		}
		result.setTotal(total);
		result.setData(list);
		return result;

	}

}
